package com.learning.servlet2x.listener;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import java.io.Serializable;
import java.util.Date;

/**
 * ClassName: ObjectListener
 * Description: 监听Session 内的对象。同时实现多个接口
 * 1、不需要web的配置
 * 2、需要使用的话，session 里面存放这个对象即可
 * Date: 2014-12-10 22:25 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class SessionObjectListener implements HttpSessionActivationListener, HttpSessionBindingListener, Serializable {

    private static final long serialVersionUID = -4780592776386225973L;

    private String name;
    private Date dateCreated;


    /**
     * 从硬盘加载后
     *
     * @param se
     */
    @Override
    public void sessionDidActivate(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        System.out.println(this + "已经成功从硬盘中加载。sessionId: " + session.getId());
    }

    /**
     * 即将被序列化到硬盘时
     *
     * @param se
     */
    @Override
    public void sessionWillPassivate(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        System.out.println(this + "即将保存到硬盘。sessionId: " + session.getId());
    }

    /**
     * 被放进session前
     *
     * @param event
     */
    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        String name = event.getName();
        System.out.println(this + "被绑定到session \"" + session.getId() + "\"的" + name + "属性上");

        // 记录放到session中的时间
        this.setDateCreated(new Date());
    }

    /**
     * 从 session 中移除后
     *
     * @param event
     */
    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        String name = event.getName();
        System.out.println(this + "被从session \"" + session.getId() + "\"的" + name + "属性上移除");
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("SessionObjectListener{");
        sb.append("name='").append(name).append('\'');
        sb.append(", dateCreated=").append(dateCreated);
        sb.append('}');
        return sb.toString();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getDateCreated() {
        return dateCreated;
    }

    public void setDateCreated(Date dateCreated) {
        this.dateCreated = dateCreated;
    }


}
